package org.kingtop.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class FileUtil {

	/**
	 * 获取一个文件夹中的文件数
	 *
	 * @param path
	 *            文件夹路径
	 * @return int
	 */
	public int getNumber(String path) {
		path = FileUtil.getPath() + path;
		File file = new File(path);
		if (file.isDirectory()) {
			String[] files = file.list();
			if (files != null) {
                return files.length;
            }
		}
		return 0;
	}

	/**
	 * 删除文件
	 *
	 * @param path
	 *            文件路径
	 * @return boolean
	 */
	public static boolean deleteFile(String path) {
		File file = new File(path);
		boolean bo = false;
		if (file.isFile() && file.exists()) {
			file.delete();
			bo = true;
		}
		return bo;
	}

	/**
	 * 删除文件夹
	 *
	 * @param path
	 *            路径 例如：d:/test/
	 * @return boolean
	 */
	public static boolean deleteDirectiory(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
            return flag;
        }
		if (!file.isDirectory()) {
            return flag;
        }

		flag = deleteAllFile(path);
		file.delete();

		return flag;
	}

	/**
	 * 删除文件夹中的所有文件
	 *
	 * @param path
	 *            路径 例如：d:/test/
	 * @return boolean
	 */
	public static boolean deleteAllFile(String path) {
		if(StringUtils.isBlank(path)) {
            return false;
        }
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
            return flag;
        }
		if (!file.isDirectory()) {
            return flag;
        }

		String[] list = file.list();
		if(list != null) {
			File temp = null;
			for (int i = 0; i < list.length; i++) {
				temp = new File(path + list[i]);
				if (temp.isFile()) {
					temp.delete();
				}
				if (temp.isDirectory()) {
					deleteAllFile(path + list[i] + "/");
					deleteDirectiory(path + list[i] + "/");
				}
			}
		}
		

		return true;
	}

	/**
	 * 复制文件夹
	 *
	 * @param sourceDir
	 *            源文件夹
	 * @param targetDir
	 *            目标文件夹
	 * @throws IOException
	 */
	public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
		// 新建目标目录
		(new File(targetDir)).mkdirs();
		// 获取源文件夹当前下的文件或目录
		File[] file = (new File(sourceDir)).listFiles();
		if (file != null && file.length > 0) {
			for (int i = 0; i < file.length; i++) {
				if (file[i].isFile()) {
					// 源文件
					File sourceFile = file[i];
					// 目标文件
					File targetFile = new File(
							new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
					copyFile(sourceFile, targetFile);
				}
				if (file[i].isDirectory()) {
					// 准备复制的源文件夹
					String dir1 = sourceDir + "/" + file[i].getName();
					// 准备复制的目标文件夹
					String dir2 = targetDir + "/" + file[i].getName();
					copyDirectiory(dir1, dir2);
				}
			}
		}
	}

	/**
	 * 复制文件
	 *
	 * @param sourceFile
	 *            源文件地址（包含后缀名）
	 * @param targetFile
	 *            目标文件地址（包含后缀名）
	 * @throws IOException
	 */
	public static void copyFile(File sourceFile, File targetFile) throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			if (!targetFile.exists()) {
				targetFile.getParentFile().mkdirs();
				targetFile.createNewFile();
			}

			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			// 关闭流
			if (inBuff != null) {
                inBuff.close();
            }
			if (outBuff != null) {
                outBuff.close();
            }
		}
	}

	/**
	 * 获取项目根目录
	 *
	 * @return String
	 */
	public static String getPath() {
		URL path = FileUtil.class.getResource("/");
		String rootPath = path.toString();
		rootPath = rootPath.substring(6, rootPath.length() - 16);
		rootPath = rootPath.replaceAll("%20", " ");
		return rootPath;
	}

	public static String getXmlString(String path, String tagName)
			throws ParserConfigurationException, SAXException, IOException {
		File file = new File(path);
		if (!file.exists()) {
            return null;
        }
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(file);
		Element element = document.getDocumentElement();
		NodeList list = element.getElementsByTagName(tagName);
		Element element1 = (Element) list.item(0);
		return element1.getChildNodes().item(0).getNodeValue();
	}

	/**
	 * 去除文件名
	 *
	 * @param path
	 * @return
	 */
	public static String getFilePath(String path) {
		if (StringUtils.isNotBlank(path)) {
			String[] list = path.split("/");
			String name = list[list.length - 1];
			int index = name.indexOf(".");
			if (index < 0) {
                return path;
            }
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i < list.length - 1; i++) {
				buffer.append(list[i] + "/");
			}
			return buffer.toString();
		} else {
			return "";
		}
	}

	/**
	 * 读取文件返回字符流
	 *
	 * @param path
	 *            文件路径
	 * @return byte[]
	 * @throws IOException
	 */
	public byte[] readFile(String path) throws IOException {
		if(StringUtils.isBlank(path)) {
            return null;
        }
		path = FileUtil.getPath() + path;
		File file = new File(path);
		if (!file.exists()) {
            return null;
        }
		BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(102400);
		byte[] temy = new byte[102400];
		int size = 0;
		while ((size = bufferedInputStream.read(temy)) != -1) {
			byteArrayOutputStream.write(temy, 0, size);
		}
		bufferedInputStream.close();
		return byteArrayOutputStream.toByteArray();
	}

	/**
	 * 获取配置文件指定属性的数值
	 * 
	 * @param fileName
	 *            文件名称
	 * @param property
	 *            属性名称
	 * @return 值
	 * @throws IOException
	 */
	public static String getProperty(String fileName, String property) throws IOException {
		Properties properties = new Properties();
		InputStream is = FileUtil.class.getClassLoader().getResourceAsStream(fileName);
		properties.load(is);
		return properties.getProperty(property);
	}

}
